import * as PIXI from "pixi.js";
import * as Matter from 'matter-js';
import { LabelScore } from "./LabelScore";
import { App } from '../system/App';
import { Background } from "./Background";
import { Scene } from '../system/Scene';
import { Hero } from "./Hero";
import { Platforms } from "./Platforms";
import { Ground } from "./Ground";
import { BasketGroup } from "@/components/pages/game/ball/comp/game/BasketGroup";
import { BasketGroupRight } from "@/components/pages/game/ball/comp/game/BasketGroupRight";
import { Timer } from "@/components/pages/game/ball/comp/game/Timer";
import { randomBetween } from "@/utils";
import { debounce } from 'lodash'
import { BasketNet } from "@/components/pages/game/ball/comp/game/BasketNet";


let coolDown = 0

export class GameScene extends Scene {
  create() {
    this.createBackground();
    this.createHero();
    this.createGround(0);
    this.createBasketGroup(0);
    this.createBasketGroupRight(0);
    this.setEvents();
    //[13]
    this.createUI();
    // this.createTimer();
    //[/13]

    this.flag = 0;
    this.cooldown = 0;

    this.currentY = 300;

    this.time = 0;
  }

  createTimer() {
    this.timer = new Timer();
    this.container.addChild(this.timer.container);
  }

  //[13]
  createUI() {
    this.labelScore = new LabelScore();
    this.container.addChild(this.labelScore);
    this.hero.sprite.on("score", () => {
      // this.basketGroup.destroy()
      App.handler.update(this.hero.score);
      this.labelScore.renderScore(this.hero.score);
    });
  }

  //[13]

  setEvents() {
    // Matter.Events.on(App.physics, 'tick', this.onSlumDunk.bind(this));
    Matter.Events.on(App.physics, 'collisionStart', this.onCollisionStart.bind(this));
  }

  onCollisionStart(event) {
    const colliders = [event.pairs[0].bodyA, event.pairs[0].bodyB];

    const hero = colliders.find(body => body.gameHero);
    const platform = colliders.find(body => body.gamePlatform);
    const rim = colliders.find(body => body.rim);

    // console.log(`hero`, hero?.position)
    // console.log(`rim`, rim?.position)
    // console.log(`this.hero.cooldown`, this.hero.cooldown)

    // if(
    //   hero && rim &&
    //   hero.position.x > rim.position.x &&
    //   hero.position.x < rim.position.x + this.basketGroup.width
    //   // &&
    //   // hero.position.y > rim.position.y &&
    //   // hero.position.y < rim.position.y + 10
    //   && this.hero.cooldown > 2
    // ) {
    //   this.hero.collectSlum(rim);
    //   this.hero.cooldown = 0;
    // }

    if (hero && platform) {
      this.hero.stayOnPlatform(platform.gamePlatform);
    }

    // const diamond = colliders.find(body => body.gameDiamond);
    //
    // if (hero && diamond) {
    //   this.hero.collectDiamond(diamond.gameDiamond);
    // }
  }

  createHero() {
    this.hero = new Hero();
    this.container.addChild(this.hero.sprite);

    this.container.interactive = true;
    this.container.on("pointerdown", () => {
      // this.hero.score +=1
      if (window.countDown > 0) {
        this.hero.startJump();
      }
    });

    // [14]
    this.hero.sprite.once("die", () => {
      App.scenes.start("Game");
    });
    // [/14]
  }


  createBackground() {
    this.bg = new Background();
    this.container.addChild(this.bg.container);
  }


  createGround() {
    this.ground = new Ground(0);
    this.container.addChild(this.ground.container);
  }

  createBasketGroup(x) {
    this.basketGroup = new BasketGroup(x, 300);
    this.container.addChild(this.basketGroup.container);
  }

  createBasketGroupRight(x) {
    this.basketGroupRight = new BasketGroupRight(
      window.innerWidth - App.config.basket.group.width, 150);
    this.container.addChild(this.basketGroupRight.container);
  }

  update(delta, time) {
    // console.log(`time`, time)
    // console.log(`delta`, delta)
    // 用户进篮的冷却
    this.cooldown += delta;
    // this.time += delta;

    // console.log(`this.time`, this.time)

    // 出现的速度方向
    let dt = this.hero.direction < 0 ? 5 : -5;

    // 篮筐左右出现
    // if (dt < 0 ) {
    //   this.basketGroupRight.update(dt, this.currentY);
    //   this.basketGroup.update(dt);
    // }else{
    //   this.basketGroup.update(dt, this.currentY);
    //   this.basketGroupRight.update(dt);
    // }

    // if (this.hero.direction > 0) {
    //   this.basketGroupRight.update(dt, this.currentY, true);
    //   this.basketGroup.update(dt, this.currentY, false);
    // }else{
    //   this.basketGroupRight.update(dt, this.currentY, false);
    //   this.basketGroup.update(dt, this.currentY, true);
    // }
    this.basketGroup.update(dt, this.currentY, this.hero.fangxiang);
    this.basketGroupRight.update(dt, this.currentY, this.hero.fangxiang);


    // 更新时间
    // this.timer.updateTimer(this.time);

    // this.bg.update(dt)


    // 处理得分的逻辑 ////////////////////////
    let group = dt > 0 ? this.basketGroup : this.basketGroupRight;

    let target = group.container.children.find(e => e.name === `basket_rim`)
    // console.log(`target`, target)

    // console.log("group", group);
    if (target) {
      let x = group.container.x + target.position.x
      let y = group.container.y + target.position.y
      // console.log(`x`, App.config.basket.rim.width, this.hero.sprite.x, this.hero.sprite.y)

      // let distance = Math.sqrt(
      //   (this.hero.sprite.x - x) ^ 2
      //   +
      //   (this.hero.sprite.y - y) ^ 2
      // );

      let dx = Math.abs(this.hero.sprite.x - this.hero.sprite.width - x);
      let dy = this.hero.sprite.y - y;
      // console.log(dx, dy, this.hero.body.velocity.y, this.hero.minHeight, y, this.hero.getscore);
      if (dx < 30 && dy > 5 && dy < 50 && this.hero.body.velocity.y >= 0 && this.hero.minHeight < y && this.hero.getscore) {
        // console.log(dx, dy, this.hero.body.velocity.y, this.hero.minHeight, y);
        // alert(dx, dy, this.hero.body.velocity.y, this.hero.minHeight, y);
        // console.log(`distance`, distance)
        // console.log(this.hero)
        this.cooldown = 0;
        this.hero.getscore = false;
        this.hero.endBall = false;
        // this.hero.collectSlum(); // 触发得分的方法 //////
        // setTimeout(()=>{
        this.hero.fangxiang = !this.hero.fangxiang;
        this.currentY = randomBetween(window.innerHeight-500, 500);
        // }, 200)

        // console.log(this.currentY, this.hero.fangxiang);
        (() => {
          if (dt > 0) this.basketGroup.fire();
          else this.basketGroupRight.fire()
          
          if (this.hero.score === 8) {
            this.container.removeChild(this.hero.sprite)
            this.container.addChildAt(this.hero.animatedSprite, 1);
            this.hero.animatedSprite.gotoAndPlay(0);
            // this.container.addChildAt(this.hero.animatedSprite, 0);
            // this.hero.animatedSprite.play();
          }

          const fn = debounce(this.hero.collectSlum.bind(this.hero), 100)
          fn()
        })()
        setTimeout(()=>{
          this.hero.endBall = true;
        }, 666);
        // this.hero.collectSlum(); // 触发得分的方法 //////
        // console.log(`hero.sprite.position`, this.hero.sprite.position.x, this.hero.sprite.position.y)
        // console.log(`position`, target.x, target.y)
      }

      // console.log("App.handler.getTime()", window.countDown);
      // 处理如果时间到了，篮球位置比蓝框高，又处于上升状态，此时等待绝杀球，如果下落低于蓝框了还没进球这时候才算结束
      if (window.countDown === 0 && window.phase === "playing") {
        // console.log(dy, this.hero.getscore, this.hero.body.velocity.y)
        if (dy > 50 && this.hero.body.velocity.y >= 0 && this.hero.endBall) {
          // console.log("aaaaaaaaaaa")
          App.handler.sendEnd();
        }else{
          // console.log(window.countDown, window.phase, this.hero.endCount);
          this.hero.endCount += 1;
          if (this.hero.endCount > 300) {
            App.handler.sendEnd();
          }
        }
      }
    }

  }

  destroy() {
    Matter.Events.off(App.physics, 'collisionStart', this.onCollisionStart.bind(this));
    App.app.ticker.remove(this.update, this);
    this.time = 0;
    this.bg.destroy();
    this.hero.destroy();
    this.basketGroup.destroy();
    this.basketGroupRight.destroy();
    this.ground.destroy();
    this.labelScore.destroy();
  }
}